from . import api
from flask import jsonify, current_app, make_response, request
from myapp.models import get_conn, ImageTable

db_session = get_conn()

@api.route("/file/<file_name>", methods=["GET"])
def get_file_image(file_name):
    try:
        with open("static/" + file_name, "rb") as f:
            image_url = f.read()
    except Exception as e:
        current_app.logger.error("图片异常，异常信息：{}".format(e))
        return jsonify(status_code=304, msg="未知图片！")
    response = make_response(image_url)
    response.headers["Content-type"] = "image/png"
    return response


@api.route("/search", methods=["POST"])
def search_image():
    
    image_tb = ImageTable.image_tb
    try:
        req_data = request.get_json()
    except Exception as e:
        current_app.logger.error("服务异常，异常信息：{}".format(e))
        return jsonify(status_code=400, msg="参数类型不合法！")

    image_name = req_data.get("image_name")
    try:
        if not image_name:
            result = db_session.execute(image_tb.select()).fetchall()
        else:
            result = db_session.execute(image_tb.select().where(image_tb.c.image_name.like('%'+image_name + '%'))).fetchall()    
    except Exception as e:
        current_app.logger.error("服务查询异常，异常信息：{}".format(e))
    data_list = []
    for rst in result:
        data_dict = {}
        for key,value in dict(rst).items():
            data_dict[key] = value
        data_list.append(data_dict)
    return jsonify(status_code=200, msg={"data":data_list})

  


